// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var dialog = require("dialog");
	var validate = require("validate");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var router = require("../hash/pageRouter");
	var css_financingDetailInfo = require("../financing/financingDetailInfo.css");
	var css_param = require("./approvelConsignment.css");
	var css_common = require("../../../css/common.css");
	var valuationCal = require("valuationCal");
	var tools = require("tools");
	var databind = require("databind");
	var constant = require("constant");
	var pickupId;
	var financeId;
	var bulkstockList;
	var $this;
    var html_bulkstockInfo = require("./html_bulkstockInfo.html");//查询货物弹出框内容
	var init = function(page) {
		pickupId = page.params.pickupId || base.getUrlParam("pickupId");
		initPickUpDetail(pickupId);
		router.init();
//		leftMenu.init(11);
		initEvent();
	};
	var initEvent = function() {
		//查看审批记录
		$("#approvelConsignment .auditRecord").unbind("click").click(function(){
//			window.open("../auditRecord/pickUpGoodsAuditRecord.html?recordType=7&recordId=" + pickupId);
			window.open("../auditRecord/auditRecord.html?recordType=7&recordId=" + pickupId);
		});
		
		$("#approvelConsignment .print").unbind("click").click(function(){
			tools.printit($("#approvelConsignment"),'preview');
		});
		
		// 商务部审核保存
		$("#businessAudit .button-Yes").unbind("click").click(function(){
			preservationBussinessAuditOpinion();
		});
		
		// 商务部审核提交
		$("#businessAudit .button-Save").unbind("click").click(function(){	
		var ii5 = layer.confirm('是否确认提交？提交后不可再次修改。', {
				  btn: ['确定','取消'] //按钮
				}, function(){
					submitBussinessAuditOpinion();
			});
		});
		
		// 商务领导审核保存
		$("#businessManageAudit .button-Yes").unbind("click").click(function(){
			preservationLeaderBussinessAuditOpinion();
		});
		
		// 商务领导审核提交
		$("#businessManageAudit .button-Save").unbind("click").click(function(){
			var ii5 = layer.confirm('是否确认提交？提交后不可再次修改。', {
				  btn: ['确定','取消'] //按钮
				}, function(){
					submitLeaderBussinessAuditOpinion();
			});
		});
		
		//  运营审核保存
		$("#operationAudit .button-Yes").unbind("click").click(function(){
			preservationOperateBussinessAuditOpinion()
		});
		
		//  运营审核提交
		$("#operationAudit .button-Save").unbind("click").click(function(){
			var ii5 = layer.confirm('是否确认提交？提交后不可再次修改。', {
				  btn: ['确定','取消'] //按钮
				}, function(){
					submitOperateBussinessAuditOpinion();
			});
		});
		
		//查看融资详情
		$("#approvelConsignment tr[class='trFinanceDetail']").hide();
		$("#approvelConsignment").on("click", ".showFinanceDetail", function() {
			var $thisParent = $(this).parents("tr");
			var financeId = $thisParent.attr("financeId");
			if($thisParent.next().is(":hidden")) {
				$thisParent.next().show();
				$(this).html("&nbsp;&nbsp;[-]");
			}else {
				$thisParent.next().hide();
				$(this).html("&nbsp;&nbsp;[+]");
			}
			
			if($thisParent.next().attr("isNull") != "1") {
				inquireFinanceApplicationDetail($thisParent.next(),financeId);
			}
		});
		
		//点击融资编号
		$("#approvelConsignment .order_num").unbind("click").click(function() {
			router.route("financing/financingDetailInfo.html?financeId=" + $(this).parents("tr").attr("financeId"));
		});
	};
	
	//提货详情
	var initPickUpDetail = function(pickupId) {
		base.fnAjax({
			action: "inquireFinancePickupApplicationWarehouse.json",
			async: false,
			oData: {
				pickupId: pickupId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					if(data.datas.length > 0) {
						
//						tools.stepBar($("#approvelConsignmentStepBar"), data.datas[0].finalId, [{name: "商务部审核", id: 25}, {name: "商务部领导审核", id: 26}, {name: "运营审核", id: 5}, {name: "风控审核", id: 3}, {name: "风控领导审核", id: 4}, {name: "资金审核", id: 9}, {name: "资金领导审核", id: 10}, {name: "副总经理审核", id: 20}, {name: "总经理审核", id: 12}]);
						var step = 1;
						if (data.datas[0].finalId == 25) {
							step = 1;
						} else if (data.datas[0].finalId == 5) {
							step = 2;
						} else if (data.datas[0].finalId == 3) {
							step = 3;
						} else if (data.datas[0].finalId == 9) {
							step = 4;
						} else if (data.datas[0].finalId == 10) {
							step = 5;
						} else if (data.datas[0].finalId == 20) {
							step = 6;
						} else if (data.datas[0].finalId == 14) {
							step = 7;
						}
						tools.stepBar($("#approvelConsignmentStepBar"), step, [{name: "商务部审核", id: 1}, {name: "运营审核", id: 2}, {name: "风控审核", id: 3}, {name: "资金审核", id: 4}, {name: "资金领导审核", id: 5}, {name: "副总经理审核", id: 6}, {name: "审核完成", id: 7}]);
						
						tools.inquireCurrentOperationList($("#approvelConsignment"));
						
						juicer.register("formatCurrency", tools.formatCurrency);
						juicer.register("getValueByKey", constant.getValueByKey);
						juicer.register("inquireFile", tools.inquireFile);
						
						var tpl = $("#approvelConsignment .tpl").html();

						var html = juicer(tpl, data);
						$("#approvelConsignment .content1").html(html);
						
						if(data.datas[0].filesUuid != undefined) {
							var filesUuid = data.datas[0].filesUuid;
							financeId = data.datas[0].bulkstockList[0].financeId;
							var tableBody = "";
							var index = 1;
							$.each(filesUuid.split(","), function() {
								var _this = this;
								if($.trim(_this) != "") {
									tableBody += '<tr><td>'+index+'</td><td>'+ tools.inquireFile(_this) +'</td><td><a target="_blank" class="table_details_link" fileUuid="' + _this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + _this + '" >' + "预览" + '</a></td></tr>';
								}
								index = index + 1;
							});
							
							$("#approvelConsignment .fileUuidBody").html(tableBody);
//							databind.disableInput($("#approvelConsignment"));
//							databind.enableInput($("#approvelConsignment .supplementOpinion"));
//							databind.enableInput($("#approvelConsignment .location"));
						}
						
						//提货信息合计
						var supervisionQuantitys = 0;
						$.each($("#approvelConsignment .supervisionQuantity"), function() {
							supervisionQuantitys += parseFloat($(this).attr("supervisionQuantity"));
						});
						$("#approvelConsignment #supervisionQuantitys").html(tools.formatCurrency(supervisionQuantitys));
						
						var pickupQuantitys = 0;
						$.each($("#approvelConsignment .pickupQuantity"), function() {
							pickupQuantitys += parseFloat($(this).attr("pickupQuantity"));
						});
						$("#approvelConsignment #pickupQuantitys").html(tools.formatCurrency(pickupQuantitys));
						
						var bulkstockAmount = 0;
						$.each($("#approvelConsignment .bulkstockAmount"), function() {
							bulkstockAmount += parseFloat($(this).attr("bulkstockAmount"));
						});
						$("#approvelConsignment #bulkstockAmount").html(tools.formatCurrency(bulkstockAmount));
						
						var interest = 0;
						$.each($("#approvelConsignment .interest"), function() {
							interest += parseFloat($(this).attr("interest"));
						});
						$("#approvelConsignment #interest").html(tools.formatCurrency(interest));
						
						var others = 0;
						$.each($("#approvelConsignment .others"), function() {
							others += parseFloat($(this).attr("others"));
						});
						$("#approvelConsignment #others").html(tools.formatCurrency(others));
						
						var pickupAmounts = 0;
						$.each($("#approvelConsignment .pickupAmount"), function() {
							pickupAmounts += parseFloat($(this).attr("pickupAmount"));
						});
						$("#approvelConsignment #pickupAmounts").html(tools.formatCurrency(pickupAmounts));
					
						tools.clearNoNumAll($("#approvelConsignment"));		
						
						databind.fillForm($("#approvelConsignment"), data.datas[0]);
						
						if(data.datas[0].submissionStatus == false){
							$("#businessManageAudit .button-submit").remove();
							$("#operationAudit .button-submit").remove();
						} else {
							$("#businessAudit .button-submit").remove();
						}
//						
//						if(data.datas[0].submissionStatus2 == false){
//							$("#operationAudit .button-submit").remove();
//						} else {
//							$("#businessManageAudit .button-submit").remove();
//						}
						
						if(data.datas[0].submissionStatus3 == false){
						} else {
							$("#operationAudit .button-submit").remove();
						}
						
						if ($("#approvelConsignment select[name=auditState]").val() == null){
							$("select[name=auditState]").html("<option>"+data.datas[0].auditState == false?"拒绝":"同意"+"</option>");
						}
						if ($("#approvelConsignment select[name=auditState2]").val() == null){
							$("select[name=auditState2]").html("<option>"+data.datas[0].auditState2 == false?"拒绝":"同意"+"</option>");
						}
						if ($("#approvelConsignment select[name=auditState3]").val() == null){
							$("select[name=auditState3]").html("<option>"+data.datas[0].auditState3 == false?"拒绝":"同意"+"</option>");
						}
				
						databind.fillForm($("#businessAudit"), {"submissionStatus_1": data.datas[0].submissionStatus == false?"待提交":"已提交"});
						databind.fillForm($("#businessManageAudit"), {"submissionStatus_2": data.datas[0].submissionStatus2 == false?"待提交":"已提交"});
						databind.fillForm($("#operationAudit"), {"submissionStatus_3": data.datas[0].submissionStatus3 == false?"待提交":"已提交"});
					}
					
					if (data.datas[0].pickupState != 2) {
						databind.disableInput($("#approvelConsignment"));
						$("#approvelConsignment .button-submit").remove();
					}
				  	
				  	$.each($("#approvelConsignment table tr"), function() {
						
						var _this = $(this)
						if (_this.attr("financeNumber") != null && _this.attr("financeNumber") != "") {
							inquireFinanceApplicationDetailByFinanceNUmber(_this.attr("financeNumber"), function(data){
						  		//回调
						  		_this.find(".financeNumber").append(data.datas[0].financeNumber + '<input type="hidden" name="financeNumbers" value="'+data.datas[0].financeNumber+'" /><input type="hidden" name="financeIds" value="'+data.datas[0].financeId+'" />');
						  		_this.find(".productType").html(constant.getValueByKey(7, data.datas[0].productType));
						  		_this.find(".financeBulkstock").html(data.datas[0].bulkstocks[0].bulkstockName + "(" + data.datas[0].bulkstocks[0].specification + ")");
						  		_this.find(".waitReceipt").html(tools.formatCurrency(data.datas[0].totalLoanAmount - data.datas[0].totalReceivedAmount));
							});
						}
			
					});
				}else {
					base.alert(2, data.message);
					return;
				}
			}
		});
	};
	
    var preservationBussinessAuditOpinion =function(){
		var auditState =$("#approvelConsignment select[name=auditState]").val();
		var auditRemark =$("#approvelConsignment textarea[name=auditRemark]").val();
		base.fnAjax({
			action : "preservationBussinessAuditOpinion.json",
			async : false, // 同步异步
			oData : {
				pickupId : pickupId,
				auditState : auditState,
				auditRemark : auditRemark
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "保存成功!");
					router.route("warehousePickup/approvelConsignment.html?pickupId=" + pickupId);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
	
	var submitBussinessAuditOpinion =function(){
		var auditState =$("#approvelConsignment select[name=auditState]").val();
		var auditRemark =$("#approvelConsignment textarea[name=auditRemark]").val();
		base.fnAjax({
			action : "submitBussinessAuditOpinions.json",
			async : false, // 同步异步
			oData : {
				pickupId : pickupId,
				auditState : auditState,
				auditRemark : auditRemark
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "保存成功!");
					router.route("warehousePickup/approvelConsignment.html?pickupId=" + pickupId);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
	
	var preservationLeaderBussinessAuditOpinion =function(){
		var auditState2 =$("#approvelConsignment select[name=auditState2]").val();
		var auditRemark2 =$("#approvelConsignment textarea[name=auditRemark2]").val();
		base.fnAjax({
			action : "preservationLeaderBussinessAuditOpinion.json",
			async : false, // 同步异步
			oData : {
				pickupId : pickupId,
				auditState2 : auditState2,
				auditRemark2 : auditRemark2
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "保存成功!");
					router.route("warehousePickup/approvelConsignment.html?pickupId=" + pickupId);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
    
	var submitLeaderBussinessAuditOpinion =function(){
		var auditState2 =$("#approvelConsignment select[name=auditState2]").val();
		var auditRemark2 =$("#approvelConsignment textarea[name=auditRemark2]").val();
		base.fnAjax({
			action : "submitLeaderBussinessAuditOpinion.json",
			async : false, // 同步异步
			oData : {
				pickupId : pickupId,
				auditState2 : auditState2,
				auditRemark2 : auditRemark2
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "保存成功!");
					router.route("warehousePickup/approvelConsignment.html?pickupId=" + pickupId);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
	
	var preservationOperateBussinessAuditOpinion =function(){
		var auditState3 =$("#approvelConsignment select[name=auditState3]").val();
		var auditRemark3 =$("#approvelConsignment textarea[name=auditRemark3]").val();
		base.fnAjax({
			action : "preservationOperateBussinessAuditOpinion.json",
			async : false, // 同步异步
			oData : {
				pickupId : pickupId,
				auditState3 : auditState3,
				auditRemark3 : auditRemark3
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "保存成功!");
					router.route("warehousePickup/approvelConsignment.html?pickupId=" + pickupId);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
    
	var submitOperateBussinessAuditOpinion =function(){
		var auditState3 =$("#approvelConsignment select[name=auditState3]").val();
		var auditRemark3 =$("#approvelConsignment textarea[name=auditRemark3]").val();
		base.fnAjax({
			action : "submitOperateBussinessAuditOpinion.json",
			async : false, // 同步异步
			oData : {
				pickupId : pickupId,
				auditState3 : auditState3,
				auditRemark3 : auditRemark3
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "保存成功!");
					router.route("warehousePickup/approvelConsignment.html?pickupId=" + pickupId);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
	
	//查询融资详情
	var inquireFinanceApplicationDetail = function(dom,financeId) {
		base.fnAjax({
			action: "inquireFinanceApplicationDetail.json",
			nocode: true,
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var d = {};
					d.loanDate = data.datas[0].loanDate;
					d.loanAmount = tools.formatCurrency(data.datas[0].loanAmount);
					d.intrerst = data.datas[0].auditInterest;
					d.pledgeRate = (parseFloat(data.datas[0].financeAuditDetail.financeAmount)*100/parseFloat(data.datas[0].bulkstocks[0].finalPrice)).toFixed(2);
					d.financeDays = data.datas[0].financeProductInnerDetail.financeDays;
					d.bulkstockPrice = tools.formatCurrency(data.datas[0].bulkstocks[0].bulkstockPrice);
					d.financePrice = tools.formatCurrency(data.datas[0].bulkstocks[0].financePrice);
					
					databind.fillForm(dom, d);
					
					dom.attr("isNull", "1");
				}else {
					//
				}
			}
		})
	};
	
	//查询融资详情
	var inquireFinanceApplicationDetailByFinanceNUmber = function(financeNumber, callback) {
//		if (financeNumber == null || financeNumber == "") {
//			base.alert(3, "请输入融资编号！");
//			return false;
//		}
		
		base.fnAjax({
			action: "inquireFinanceApplicationDetailByFinanceNUmber.json",
			nocode: true,
			oData: {
				financeNumber: financeNumber
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
//					var d = {};
//					d.loanDate = data.datas[0].loanApplicationCreateDatetime;
//					d.loanAmount = tools.formatCurrency(data.datas[0].financeAmount);
//					d.interestRate = data.datas[0].auditInterest + "%";
//					d.financeDays = data.datas[0].financeProductInnerDetail.financeDays;
//					d.financeNumbers = data.datas[0].financeNumber;
//					d.financeIds = data.datas[0].financeId;
//					d.productType = constant.getValueByKey(7, data.datas[0].productType);
//					d.bulkstockName= data.datas[0].bulkstocks[0].bulkstockName + "("　+ data.datas[0].bulkstocks[0].specification +　")";
//					d.financeContractSerialNumber = data.datas[0].financeContractDetail.financeContractSerialNumber;
//					d.waitReceipt = data.datas[0].financeAmount-data.datas[0].totalReceivedAmount;
//					d.deadLine = tools.addDate(data.datas[0].loanApplicationCreateDatetime, data.datas[0].financeProductInnerDetail.financeDays);
//					
//					databind.fillForm(dom, d);
					callback(data);
				}else {
					base.alert(3, data.message);
				}
			}
		})
	};
	
	return {
		init: init
	};
});